package com.qf.service.impl;

import com.qf.constant.CacheConstants;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import com.qf.service.FilterChainManager;
import com.qf.service.FilterChainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 *
 * 策略执行管理器
 * @author YDW
 * projectName:project2202_4
 * time:2022/6/20 22:38
 * description:
 */
@Service
@Slf4j
public class FilterChainManagerImpl implements FilterChainManager {

    //@AutoWired: 注入所有的策略模式对象
    //以 对象的名称为key，以策略模式对象为value，注入到map集合中
    @Autowired
    Map<String, FilterChainService> filterMap;

    @Autowired
    CacheFeign cacheFeign;


    //执行策略
    @Override
    public void execute(StandardSubmit submit) {

        //1. 获取该客户端需要的策略（调用cache模块）
        String key= CacheConstants.CACHE_PREFIX_CLIENT+submit.getClientID();
        String filed="filters";
        String filters =cacheFeign.hgetStr(key, filed);
        //2.遍历执行需要的策略
        if(!StringUtils.isEmpty(filters)){
            String[] filterArr = filters.split(",");
            for (String filter : filterArr) {
                //从所有的策略对象中，根据策略对象名称，获取策略对象
                FilterChainService filterChainService = filterMap.get(filter);
                //执行策略
                if (filterChainService != null) {
                    boolean flag = filterChainService.strategy(submit);
                    //如果某策略执行异常，则结束责任链流程
                    if(!flag){
                        log.info("[策略模块 -- 策略模块] 执行策略完成");
                        break;
                    }
                }

            }
        }
    }
}
